package com.basedefence;

import com.badlogic.gdx.math.Vector2;
import com.e3roid.drawable.sprite.AnimatedSprite;

interface RocketState
{
	final static int idle = 0;
	final static int dieAnim = 1;
	final static int died = 2;
}

public class Rocket
{
	private int speed; //pixels per second
	private float angle;
	private Vector2 direction;
	private Vector2 position;
	private AnimatedSprite sprite;
	private int state;
	private int dieTimer;
	
	public boolean wasTapped;
	
	public float getAngle() 
	{
		return angle;
	}
	
	public void setAngle (float angle)
	{
//		this.angle = angle;
//		sprite.rotate(angle);
		setDirection(Utils.angle2Direction(angle), true);
	}

	public void addAngle (float deltaAngle)
	{
		setAngle(angle + deltaAngle);
	}

	public int getSpeed()
	{
		return speed;
	}

	public void setSpeed(int speed) 
	{
		this.speed = speed;
	}

	public Rocket ()
	{
		position = new Vector2();
		state = RocketState.idle;
	}
	
	public void setDirection (Vector2 vector, boolean rotateSprite)
	{
		setDirection(vector.x, vector.y, rotateSprite);
	}
	
	public void setDirection (float x, float y, boolean rotateSprite)
	{
		if (direction == null)
			direction = new Vector2();
		
		direction.set(x, y);
		
		angle = Utils.direction2Angle(x, y);
		sprite.rotate(angle - 90);
	}
	
	public float getDirectionX ()
	{
		return direction.x;
	}
	
	public float getDirectionY ()
	{
		return direction.y;
	}
	
	public Vector2 getDirection ()
	{
		return direction;
	}
	
	public void setSprite (AnimatedSprite newSprite)
	{
		sprite = newSprite;
		setPosition(sprite.getRealX(), sprite.getRealY());
	}
	
	public AnimatedSprite getSprite ()
	{
		return sprite;
	}
	
	public void update (long elapsedTime)
	{
		if (state == RocketState.idle)
		{
			float dx = direction.x * speed * elapsedTime / 1000;
			float dy = direction.y * speed * elapsedTime / 1000;
			
			position.x += dx;
			position.y += dy;
			
			sprite.move((int)position.x, (int)position.y);
	//		sprite.move(0,0);
		}
		else
		{
			dieTimer -= elapsedTime;
			
			if (dieTimer % 400 > 200)
				sprite.show();
			else
				sprite.hide();
			
			if (dieTimer < 0)
				state = RocketState.died;
		}
	}
	
	public void setPosition (int x, int y)
	{
		position.x = x;
		position.y = y;
	}
	
	public void destroy ()
	{
		state = RocketState.dieAnim;
		dieTimer = 1000;
		sprite.setAlpha(0.5f);
	}
	
	public int getState ()
	{
		return state;
	}
}
